﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace ARA.WebApp
{
    public partial class Upload : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void ctlBtnSubmit_Click(object sender, EventArgs e)
        {
            bool hasError = false;
            string tempDir = System.Configuration.ConfigurationManager.AppSettings["ARA.TEMP"];
            if(!System.IO.Directory.Exists(tempDir))
            {
                Directory.CreateDirectory(tempDir);
            }

            string tempFile = string.Format("{0}{1}.temp",tempDir, Guid.NewGuid().ToString("N"));
            try
            {
                ctlFileUpload.SaveAs(tempFile);
                LoadAndInsert(tempFile);
            }
            catch(Exception ex)
            {
                hasError = true;
            }
            finally
            {
                if(File.Exists(tempFile))
                {
                    try
                    {
                        File.Delete(tempFile);
                    }
                    catch (Exception ex)
                    {
                    }
                }
            }

            if(hasError)
            {
                Response.Redirect("~/Error.aspx");
            }
        }

        private void LoadAndInsert(string filePath)
        {
            DataTable dataTable = CPPEI.ETL.Infrastructure.Excel.OpenXmlTool.ReadDataTable(filePath);

            // 去除无效的列
            // A:用户名	
            // B:全名	
            // C:用户组	
            // D;在线	
            // E:终端名	
            // F:主机名	
            // G:登录时间
            // H:下线时间
            // I:IP地址
            // J:子网
            // A,B,E,F,I都不能为空

            for (int index = 0; index < dataTable.Rows.Count; )
            {
                bool isDeleted = false;
                string value = Convert.ToString(dataTable.Rows[index]["A"]);
                if (string.IsNullOrEmpty(value) || value.Contains("@") == false)
                {
                    // remove
                    dataTable.Rows.RemoveAt(index);
                    isDeleted = true;
                }
                if (isDeleted == false)
                {
                    value = Convert.ToString(dataTable.Rows[index]["B"]);
                    if (string.IsNullOrEmpty(value))
                    {
                        // remove
                        dataTable.Rows.RemoveAt(index);
                        isDeleted = true;
                    }
                }
                if (isDeleted == false)
                {
                    value = Convert.ToString(dataTable.Rows[index]["E"]);
                    if (string.IsNullOrEmpty(value))
                    {
                        // remove
                        dataTable.Rows.RemoveAt(index);
                        isDeleted = true;
                    }
                }

                if (isDeleted == false)
                {
                    index++;
                }
            }

            // insert to db
            bool hasError = false;
            Guid batchId = Guid.NewGuid();
            using (ARA.Domain.Services.AddRecordService service = new Domain.Services.AddRecordService())
            {
                for (int index = 0; index < dataTable.Rows.Count; index++)
                {
                    //  A:用户名	  B:全名	  C:用户组	  D;在线	 E:终端名	  F:主机名	 G:登录时间 H:下线时间 I:IP地址 J:子网
                    ARA.Domain.Entities.Record record = new Domain.Entities.Record();
                    record.Id = Guid.NewGuid();
                    record.BatchId = batchId;
                    record.Account = Convert.ToString(dataTable.Rows[index]["A"]);
                    record.Name = Convert.ToString(dataTable.Rows[index]["B"]);
                    record.Group = Convert.ToString(dataTable.Rows[index]["C"]);
                    record.Online = Convert.ToString(dataTable.Rows[index]["D"]);
                    record.Client = Convert.ToString(dataTable.Rows[index]["E"]);
                    record.Computer = Convert.ToString(dataTable.Rows[index]["F"]);
                    double dValue = 0;
                    if (double.TryParse(Convert.ToString(dataTable.Rows[index]["G"]), out dValue))
                    {
                        record.LoginTime = DateTime.FromOADate(dValue);
                    }
                    if (double.TryParse(Convert.ToString(dataTable.Rows[index]["H"]), out dValue))
                    {
                        record.LogoutTime = DateTime.FromOADate(dValue);
                    }
                    record.IP = Convert.ToString(dataTable.Rows[index]["I"]);
                    record.Net = Convert.ToString(dataTable.Rows[index]["J"]);
                    record.Index = index;
                    service.Add(record);
                }
                if (service.Commit() == false)
                {
                    hasError = true;
                }
            }


            ARA.Domain.Entities.Batch batch = new Domain.Entities.Batch();
            batch.Id = batchId;
            batch.Creator = "admin";
            batch.CreatedTime = DateTime.Now;
            if (hasError)
            {
                batch.Status = ARA.Domain.Def.BatchStatus.HasError;
            }
            else
            {
                batch.Status = ARA.Domain.Def.BatchStatus.NoError;
            }
            if(new ARA.Domain.Services.AddService().AddBatch(batch) )
            {
                Response.Redirect(string.Format("~/BatchDetail.aspx?batchid={0}", batchId));
            }
            else
            {
                Response.Redirect("~/Error.aspx");
            }
        }
    }
}